import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import Media from 'react-media';
import { Form, Input, Select, DatePicker, Button, Badge } from 'antd';
import AdSearch from '@/components/AdSearch';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ETCChangeDetails from './ETCChangeDetails';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import { billStateList, billStateOnlyReadList } from '@/utils/constans';
import { vitifyCheck, formateDateToMin } from '@/utils/common';
import prompt from '@/components/Prompt';
import SearchSelect from '@/components/SearchSelect';
import { columns1, columnsBillNo } from '@/pages/Common/common';
import FileImport from '@/components/FileImport';
import { number } from 'prop-types';
import FileReader from '@/components/FileReader';


const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

@ManageList
@connect(({ manageEtc, component, common, loading }) => ({
  manageEtc,
  ownCompany: common.ownCompany,
  searchValue: component.searchValue,
  loading: loading.effects['manageEtc/etcChangeList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class ETCChangeList extends Component {
  state = {
    expandForm: false,
    visible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    cardNo: '',
    cars: [],
    billNos: [],
    visibleFile: false,
    selectedRows: [],
    isBillStatus: '',
  };
  className = 'ETCChangeList';
  // 新增字段：入口时间 、 入口站 、 出口时间\消费时间 、消费站\出口站 、交易省份 、交易性质
  columns = [
    {
      title: '单据号',
      dataIndex: 'etcChangeNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '状态',
      dataIndex: 'billStatus',
      render: (text, record) => (
        <AdSelect
          onlyRead={true}
          value={text ? text : record.status}
          data={billStateOnlyReadList}
        />
      ),
      width: 100,
    },
    {
      title: '卡号',
      dataIndex: 'etcNo',
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '交易省份',
      dataIndex: 'locationName',
    },
    {
      title: '交易性质',
      dataIndex: 'tradingType',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['ETC_CHANGE_TYPE']} />
      ),
    },
    {
      title: '附件',
      dataIndex: 'attaQuantity',
      width: 80,
      render: (text, record) =>
          text &&
          Number(text) > 0 && (
              <Badge className="cus_badge" count={text}>
                  <div className="head-example">
                      <FileReader
                          type="list"
                          count={text}
                          urlType="tms"
                          params={{ bizId: record.id, fileBizType: 'ETC_CHANGE_MANA' }}
                      />
                  </div>
              </Badge>
          ),
  },
    {
      title: '入口时间',
      dataIndex: 'entranceTime',
    },
    {
      title: '入口站',
      dataIndex: 'entranceStation',
    },
    {
      title: ' 出口时间/交易时间',
      dataIndex: 'exportTime',
    },
    {
      title: '出口站/充值地点',
      dataIndex: 'exportStation',
    },

    {
      title: '币种',
      dataIndex: 'currencyType',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
      ),
      width: 100,
    },
    {
      title: '金额',
      dataIndex: 'changeMoney',
    },
    {
      title: '账单号',
      dataIndex: 'billNo',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];
  componentDidMount() {
    const { dispatch } = this.props;
    this.getETCChangeList();
    // 查询字典：
    //币种：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
    // 交易性质：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'ETC_CHANGE_TYPE' },
    });
  }

  getETCChangeList = params => {
    const { dispatch, searchValue } = this.props;

    dispatch({
      type: 'manageEtc/etcChangeList',
      payload: params || {},
      callback: data => {
        if (!data) return;
        let valueList = [];
        data.map(v => {
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: { params: { loginName: v[item] }, url: 'tms/tms-etc-change/etcUser_s' },
                });
            }
          });
        });
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
      cars: [],
      billNos: [],
    });
    this.getETCChangeList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { cars, billNos } = this.state;
    const { happenTime, ...value } = values;
    if (happenTime) {
      value.happenStartTime = moment(happenTime[0]).format(dateFormat);
      value.happenEndTime = moment(happenTime[1]).format(dateFormat);
    }
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    if (billNos.length > 0) {
      const billId = billNos.map(v => {
        return v.id;
      });
      value.billId = billId.join(',');
    } else {
      value.billId = '';
    }
    this.setState({
      formValues: value,
    });
    this.getETCChangeList(value);
  };

  //新建
  handleAdd = () => {
    // 设置id
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'manageEtc/setId',
    //   payload: { id: -1 },
    // });
    router.push(`/carDaily/manageEtc/etcChangeList/addETCChange`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/carDaily/manageEtc/etcChangeList/editETCChange/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.getETCChangeList(params);
  };

  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id, billStatus, cardNo } = record;
    const status = billStatus ? billStatus : record.status;
    const isBillStatus = status === 'CONFIRM' || status === 'WAIT';
    dispatch({
      type: 'manageEtc/etcChangetDetails',
      payload: { id: id },
    });
    this.setState(
      {
        isBillStatus,
        checkId: id,
        cardNo: cardNo,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };
  //导入
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };
  handleSelectRows = selectedRows => {
    this.setState({
      selectedRows,
    });
  };

  /**
   * 生成账单
   */
  generatedBills = () => {
    const { dispatch } = this.props;
    const { selectedRows, formValues } = this.state;
    const checkBill = this.checkBill();
    if (!checkBill) return;
    dispatch({
      type: 'manageEtc/generatedBills',
      payload: { ids: selectedRows.map(v => v.id) },
      callback: data => {
        if (!data) return;
        this.setState({
          selectedRows: [],
        });
        this.getETCChangeList(formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };

  /**
   * 生成账单校验 状态已提交，同一公司，同一加油方式
   */

  checkBill = () => {
    const { selectedRows } = this.state;
    const ownCompanyName = vitifyCheck({
      selectedRows,
      key: 'ownCompanyName',
      warn: '所选记录必须所属公司相同！',
    });
    const tradingType = vitifyCheck({
      selectedRows,
      key: 'tradingType',
      warn: '所选记录必须交易性质相同！',
    });

    if (!ownCompanyName || !tradingType) return false;
    return true;
  };

  selectAll = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'manageEtc/selectAll',
      payload: formValues,
      callback: data => {
        this.setState({
          selectedRows: [],
        });
        if (!data) return;
        this.getETCChangeList(formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };

  render() {
    const {
      loading,
      manageEtc: { etcChangeList, etcChangetDetails },
      form,
      isMobile,
      dictObject,
      ownCompany,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      checkId,
      cardNo,
      visible,
      visibleFile,
      expandForm,
      selectedRows,
      formValues,
      isBillStatus,
    } = this.state;
    const selectDetails = etcChangetDetails[checkId];
    const commonParams = {
      getFieldDecorator,
    };
    const firstFormItem = (
      <FormItem label="单据号">
        {getFieldDecorator('etcChangeNo')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="billStatus" {...commonParams}>
        <AdSelect data={billStateList} isExist={true} mode="multiple" />
      </AntdFormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="ETC卡号">
          {getFieldDecorator('etcNo')(<Input placeholder="请输入" />)}
        </FormItem>,
      ],
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            <SearchSelect
              dataUrl="tms/tms-etc-change/vehicleList_s" //接口还没发
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={values => this.getValue(values, 'cars')} // 获取选中值
              scrollX={480}
              id="etcChange_1"
              allowClear={true}
            />
          )}
        </FormItem>,
        <FormItem label="所属公司">
          {getFieldDecorator('mdsCompanyId')(
            <Select
              allowClear={true}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="">请选择</Option>
              {ownCompany &&
                ownCompany.map((v, i) => {
                  return (
                    <Option key={i} value={v.customerCode}>
                      {v.customerName}
                    </Option>
                  );
                })}
            </Select>
          )}
        </FormItem>,
        <FormItem label="交易时间">
          {getFieldDecorator('happenTime')(<RangePicker style={{ width: '100%' }} />)}
        </FormItem>,
      ],
      [
        <FormItem label="账单号">
          {getFieldDecorator('billId')(
            <SearchSelect
              dataUrl="tms/tms-etc-change/selectBillList_s"
              selectedData={this.state.billNos} // 选中值
              multiple={false} // 是否多选
              showValue="billNo"
              searchName="billNo"
              columns={columnsBillNo} // 表格展示列
              onChange={values => this.getValue(values, 'billNos')} // 获取选中值
              scrollX={200}
              id="etcChange_2"
              allowClear={true}
              payload={{ type: 'ETCCHANGE' }}
            />
          )}
        </FormItem>,
        <AntdFormItem label="交易性质" code="tradingType" {...commonParams}>
          <AdSelect data={dictObject['ETC_CHANGE_TYPE']} isExist={true} />
        </AntdFormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      code: codes.add,
      selectedLength: selectedRows.length,
      pagination: etcChangeList.pagination,
      selectAll: this.selectAll,
      code: codes.bill,
      buttons: (
        <Button.Group>
          <AdButton onClick={() => this.handleImportFile()} text="导入" code={codes.upload} />
          <AdButton
            disabled={!selectedRows.length > 0}
            onClick={() => this.generatedBills()}
            text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
            code={codes.bill}
          />
        </Button.Group>
      ),
    };

    const rightDrawParams = {
      isMobile,
      visible,
      code: codes.showDetail,
      title: 'ETC交易详情',
      closeDetail: this.closeDetail,
      buttons: (
        <AdButton
          onClick={this.handleEdit}
          disabled={!isBillStatus}
          text="编辑"
          type="primary"
          code={codes.edit}
        />
      ),
    };
    const billStatus = formValues.billStatus;
    return (
      <Fragment>
        <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`tms/tms-etc-change/importEtcChangeDetail`}
          // urlQuery={[{ url: `tms/tms-etc-change/selectList`, payload: {} }]}
          queryData={[this.getETCChangeList]}
        />
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          getCheckboxProps={record => {
            const status = record.billStatus ? record.billStatus : record.status;
            const checked = status === 'CONFIRM' || status === 'WAIT';
            return !checked;
          }}
          loading={loading}
          disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
          selectedRows={selectedRows}
          data={etcChangeList}
          columns={this.columns}
          expandForm={expandForm}
          onSelectRow={this.handleSelectRows}
          className={this.className}
          onPaginationChange={this.handleStandardTableChange}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <ETCChangeDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
      </Fragment>
    );
  }
}
